package org.fle4y.common.utils.basic;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;



/**
 * author : xiehui<br>
 * company : northking <br>
 * Create at: 2012-5-25
 * @version : 1.0<br>
 * 
 * Description : 封装常见的字符串操作
 */
public class StringUtil {
	
	/**
	 * 银行业务中 行的首字母一般为 h
	 */
	static final char HANG = '行';
	
	/**
	 * 国标码和区位码转换常量
	 */
	static final int GB_SP_DIFF = 160;
	
	/**
	 * 存放国标一级汉字不同读音的起始区位码
	 */ 
	static final int[] secPosValueList = { 1601, 1637, 1833, 2078, 2274, 2302,
			2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858, 4027,
			4086, 4390, 4558, 4684, 4925, 5249, 5600 };
	
	/**
	 * 存放国标一级汉字不同读音的起始区位码对应读音
	 */
	static final char[] firstLetter = { 'a', 'b', 'c', 'd', 'e', 'f', 
			'g', 'h',	'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'w', 'x',
			'y', 'z' };
	
	// 获取一个字符串的拼音码
	public static String getFirstLetter(String oriStr) {
		String str = oriStr.toLowerCase();
		StringBuffer buffer = new StringBuffer();
		char ch;
		char[] temp;
		for (int i = 0; i < str.length(); i++) { // 依次处理str中每个字符
			ch = str.charAt(i);
			temp = new char[] { ch };
			byte[] uniCode = new String(temp).getBytes();
			if (uniCode[0] < 128 && uniCode[0] > 0) { // 非汉字
				buffer.append(temp);
			} else {
				if (HANG == ch) {
					buffer.append("h");
				} else {
					buffer.append(convert(uniCode));
				}
			}
		}
		return buffer.toString();
	}

	/**
	 * 获取一个汉字的拼音首字母。 GB码两个字节分别减去160，转换成10进制码组合就可以得到区位码
	 * 例如汉字“你”的GB码是0xC4/0xE3，分别减去0xA0（160）就是0x24/0x43
	 * 0x24转成10进制就是36，0x43是67，那么它的区位码就是3667，在对照表中读音为‘n’
	 */
	static char convert(byte[] bytes) {
		char result = '-';
		int secPosValue = 0;
		int i;
		for (i = 0; i < bytes.length; i++) {
			bytes[i] -= GB_SP_DIFF;
		}
		secPosValue = bytes[0] * 100 + bytes[1];
		for (i = 0; i < 23; i++) {
			if (secPosValue >= secPosValueList[i]
					&& secPosValue < secPosValueList[i + 1]) {
				result = firstLetter[i];
				break;
			}
		}
		return result;
	}

	/**
	 *  根据输入的格式将字符串转换为日期类型.
	 * @param input   
	 * @param dateFormat 
	 * @return  
	 */
	public static boolean isDate(String input, String dateFormat) {
		
		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
		formatter.setLenient(false);
		try {
			formatter.format(formatter.parse(input));
		}catch (Exception e) {
			return false;
		}
		return true;
	}
	
	/**
	 *  将字符串从原日期格式转换为新格式.
	 * @param input
	 * @param inDateFormat
	 * @param outDateFormat
	 * @return
	 */
	public static String transforDate(String input, String inDateFormat,
			String outDateFormat) {
		
		SimpleDateFormat formatterIn = new SimpleDateFormat(inDateFormat);
		SimpleDateFormat formatterOut = new SimpleDateFormat(outDateFormat);
		formatterIn.setLenient(false);
		try {
			return formatterOut.format(formatterIn.parse(input));
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 判断字符串是否数字串
	 * @param input
	 * @return boolean 是数字串返回true，否则返回false
	 */
	public static boolean isDigitStr(String input) {
		if (input == null || input.length() == 0) {
			return false;
		}
		return input.matches("[0-9]+");
	}
	
	/**
	 * 判断字符串是否是钱的计量(最多带两位小数的浮点数)
	 * @param input
	 * @return boolean 是钱串返回true，否则返回false
	 */
	public static boolean isMoney(String input) {
		if (input == null || input.length() == 0) {
			return false;
		}
		String reg = "[0]|[1-9][0-9]*|[1-9][0-9]*[.][0-9]?[0-9]?|0[.][0-9]?[0-9]?|[.][0-9][0-9]?";
		return input.matches(reg);
	}
	
	/**
	 * 将utf-8字符串转换成gb2312编码字符串 用于将用户输入的中文信息转换后存入数据库。
	 * @param utf8
	 * @return gb2312 返回gb2312编码的字符串
	 * @exception UnsupportedEncodingException
	 *                不支持编码；类型
	 */
	public static String strToChinese(String utf8)
			throws UnsupportedEncodingException {
		if (utf8 == null) {
			return null;
		}
		byte[] bt = utf8.getBytes("ISO-8859-1");
		String gb2312 = new String(bt, "GB2312");
		return gb2312;
	}
	
	/**
	 * 将gb2312编码字符串转换成utf-8字符串 用于将数据库用户输入的中文信息转换后存入。
	 * @param str utf-8 字符串
	 * @return String 返回gb2312编码的字符串
	 * @exception UnsupportedEncodingException
	 *                不支持编码；类型
	 */
	public static String strToISO(String str)
			throws UnsupportedEncodingException {
		if (str == null || str.equals("")) {
			return "";
		}
		byte[] bt = str.getBytes("GB2312");
		String str2 = new String(bt, "ISO-8859-1");
		return str2;
	}

	/**
	 * 将中文字符串按GBK编码方式转换成16进制(以0-9,A-F格式)
	 * @param s 中文字符串
	 * @return 16进制编码串
	 * @throws UnsupportedEncodingException
	 *             系统不支持编码方式
	 */
	public static String chineseStrToHex(String s)
			throws UnsupportedEncodingException {
		if (s == null || s.length() == 0) {
			return s;
		}
		byte[] bytes = s.getBytes("GBK");
		String result = "";
		for (int i = 0; i < bytes.length; i++) {
			result += byteToHex(bytes[i]); // 转换成16进制
		}
		return result;
	}

	/**
	 * 将以GBK编码方式转换成的以十六进制格式存在的字符串，恢复为原来的字符串
	 * @param s
	 *            String 16进制编码串
	 * @throws UnsupportedEncodingException
	 *             系统不支持编码方式

	 * @return String 中文字符串

	 */
	public static String hexStringToChinese(String s)
			throws UnsupportedEncodingException {
		if (s == null || s.length() == 0) {
			return s;
		}
		int length = s.length();
		byte bytes[] = new byte[length / 2];
		int bFirst = 0;
		int bSecond = 0;
		for (int i = 0; i < s.length(); i += 2) {
			bFirst = hexToByte(s.charAt(i));
			bSecond = hexToByte(s.charAt(i + 1));
			bFirst = bFirst << 4;
			bytes[i / 2] = (byte) (bFirst | bSecond);
		}
		return new String(bytes, "GBK");
	}
	private static String byteToHex(int b) {
		int bFirst = b;
		int bSecond = b;
		bFirst = bFirst >> 4;
		bFirst = bFirst & 15;
		bSecond = bSecond & 15;
		return byteToHex2(bFirst) + byteToHex2(bSecond);
	}
	private static String byteToHex2(int b) {
		if (b == 10) {
			return "A";
		} else if (b == 11) {
			return "B";
		} else if (b == 12) {
			return "C";
		} else if (b == 13) {
			return "D";
		} else if (b == 14) {
			return "E";
		} else if (b == 15) {
			return "F";
		} else if (b < 10) {
			return "" + b;
		} else {
			return null;
		}
	}
	private static byte hexToByte(char hex) {
		switch (hex) {
		case '0':
			return 0;
		case '1':
			return 1;
		case '2':
			return 2;
		case '3':
			return 3;
		case '4':
			return 4;
		case '5':
			return 5;
		case '6':
			return 6;
		case '7':
			return 7;
		case '8':
			return 8;
		case '9':
			return 9;
		case 'A':
			return 10;
		case 'B':
			return 11;
		case 'C':
			return 12;
		case 'D':
			return 13;
		case 'E':
			return 14;
		case 'F':
			return 15;
		}
		return 0;
	}
	
	/**
	 * 将字符串的数字转化为会计格式
	 * @param str
	 * @return
	 */
	public static String formatStrToNumber(String str) {
		DecimalFormat df = new DecimalFormat();
		try {
			return df.format(Double.parseDouble(str));
		}
		catch (java.lang.NumberFormatException ex)
		{
			return "";
		}
	}
	
	/**
	 * 将会计字符串转化为数值
	 * @param str
	 * @return
	 */
	public static double transStrToNumber(String str) {
		try {
			return Double.parseDouble(str.replaceAll(",", ""));
		}
		catch (java.lang.NumberFormatException ex)
		{
			return 0;
		}
		
	}
	/**
	 * ajax 提交中文转码
	 * @param s
	 * @return
	 */
	public static String unescape(String s) {
		StringBuffer sbuf = new StringBuffer();
		int i = 0;
		int len = s.length();
		while (i < len) {
			int ch = s.charAt(i);
			if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was
				sbuf.append((char) ch);
			} else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was
				sbuf.append((char) ch);
			} else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was
				sbuf.append((char) ch);
			} else if (ch == '-' || ch == '_' // unreserved : as it was
					|| ch == '.' || ch == '!' || ch == '~' || ch == '*' || ch == '\'' || ch == '(' || ch == ')') {
				sbuf.append((char) ch);
			} else if (ch == '%') {
				int cint = 0;
				if ('u' != s.charAt(i + 1)) { // %XX : map to ascii(XX)
					cint = (cint << 4) | val[s.charAt(i + 1)];
					cint = (cint << 4) | val[s.charAt(i + 2)];
					i += 2;
				} else { // %uXXXX : map to unicode(XXXX)
					cint = (cint << 4) | val[s.charAt(i + 2)];
					cint = (cint << 4) | val[s.charAt(i + 3)];
					cint = (cint << 4) | val[s.charAt(i + 4)];
					cint = (cint << 4) | val[s.charAt(i + 5)];
					i += 5;
				}
				sbuf.append((char) cint);
			} else { // 对应的字符未经过编码
				sbuf.append((char) ch);
			}
			i++;
		}
		return sbuf.toString();
	}

	private final static byte[] val = { 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00,
			0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B,
			0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
			0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F };

	/**
	 * 构造Ajax返回字符串
	 * @param ajaxString
	 * @param name
	 * @param value
	 * @return
	 */
	public static String getAjaxString(String ajaxString, String name, String value) {
		if (ajaxString == null)
			ajaxString = "";
		ajaxString += "[" + name + ":" + value + "]";
		return ajaxString;
	}
	
	/**清除右边空白*/
    public static String rtrim(String s) {
    	if (s == null) {
    	    return s;
    	}
    	int i = s.length() - 1;
    	while (i >= 0 && s.charAt(i) <= ' ') {
    	    i--;
    	}
    	return i == s.length() ? s : s.substring(0, i + 1);
        }
	

}
